package request

import (
	"encoding/json"
	"fmt"

	"github.com/micro-plat/hydra"
	"github.com/micro-plat/lib4go/types"
)

type RequestResult struct {
	Result string `json:"result"`
	Msg    string `json:"msg"`
}

// Request rpc请求
func Request(info interface{}, url string) (r *RequestResult, err error) {

	requestData, err := types.Struct2Map(info)
	if err != nil {
		return
	}

	response, err := hydra.C.RPC().GetRegularRPC().Request(url, requestData)
	if err != nil || response.GetStatus() != 200 {
		return nil, fmt.Errorf("记账请求错误,url:%s,params:%+v,err:%+v,response:%+v", url, requestData, err, response)
	}

	r = &RequestResult{}

	if err = json.Unmarshal([]byte(response.GetResult().(string)), r); err != nil {
		return nil, fmt.Errorf("记账返回错误,response:%+v,err:%+v", response, err)
	}

	return
}

// RequestDirect rpc
func RequestDirect(requestData types.XMap, url string) (r string, err error) {

	response, err := hydra.C.RPC().GetRegularRPC().Request(url, requestData)

	if err != nil || response.GetStatus() != 200 {
		return "", fmt.Errorf("记账请求错误,url:%s,params:%+v,err:%+v,response:%+v", url, requestData, err, response)
	}
	return response.GetResult().(string), nil
}
